package com.wbl.featurn.login

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wbl.common.UiEffect
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(
    val loginCase: LoginCase
) : ViewModel() {
    private val _uiState = MutableStateFlow(LoginUiState())
    val uiState: StateFlow<LoginUiState> = _uiState.asStateFlow()

    private val _effect = Channel<UiEffect>(Channel.BUFFERED)
    val effect = _effect.receiveAsFlow()

    fun handleIntent(intent: LoginIntent) {
        when (intent) {
            is LoginIntent.UpdateUserName -> {
                _uiState.update {
                    it.copy(
                        username = intent.userName
                    )
                }
            }

            is LoginIntent.UpdatePassword -> {
                _uiState.update {
                    it.copy(
                        password = intent.password
                    )
                }
            }

            is LoginIntent.Login -> {
                login()
            }
        }
    }

    fun login() {
        _uiState.update { it -> it.copy(loading = true, error = null) }
        viewModelScope.launch {
            val result = loginCase.invoke(_uiState.value.username, _uiState.value.password)
            result.fold(
                onSuccess = {
                    _uiState.update {
                        it.copy(
                            loading = false,
                            success = true,
                            error = null
                        )
                    }
                },
                onFailure = { e ->
                    _uiState.update {
                        it.copy(
                            loading = false,
                            success = false,
                            error = e.message ?: "未知错误"
                        )
                    }
                    _effect.send(UiEffect.ShowToast(e.message ?: "未知错误"))

                }
            )
        }
    }
}

data class LoginUiState(
    val username: String = "",
    val password: String = "",
    val loading: Boolean = false,
    val error: String? = null,
    val success: Boolean = false
)

sealed class LoginIntent {
    data class UpdateUserName(val userName: String) : LoginIntent()
    data class UpdatePassword(val password: String) : LoginIntent()
    object Login : LoginIntent()
}